import type { AxiosResponse } from 'axios'
import request from '../utils/request'
import type { ApiResponse } from '@/types'
import type { UserInfo } from '@/types/user'
import type { PurchaseRequestItem } from '@/types/request'

export interface LoginParams {
    username: string
    password: string
}

export interface RegisterParams {
    username: string
    password: string
    phone: string
    code: string
    school: string
}

export interface ResetPasswordParams {
    phone: string
    code: string
    newPassword: string
}

export interface ApiResponse<T> {
    code: number
    data: T
    message: string
}

export interface UserInfo {
    id: number
    username: string
    nickname: string
    avatar?: string
    role: string
    token: string
}

export interface PaginationParams {
    page?: number
    pageSize?: number
}

export interface ProductItem {
    id: number
    title: string
    price: number
    status: string
    images: string[]
    description: string
    createdAt: string
    viewCount: number
    [key: string]: any
}

export interface OrderItem {
    id: number
    orderNo: string
    amount: number
    status: string
    products: any[]
    createdAt: string
    [key: string]: any
}

export interface FavoriteItem {
    id: number
    productId: number
    title: string
    price: number
    image: string
    [key: string]: any
}

export interface MessageItem {
    id: number
    title: string
    content: string
    time: string
    read: boolean
    [key: string]: any
}

export interface WalletTransaction {
    id: number
    amount: number
    type: string
    time: string
    description: string
    [key: string]: any
}

export interface UserProfile {
    id: number
    username: string
    nickname: string
    avatar?: string
    school?: string
    balance: number
    messageCount: number
    reputation?: number
    [key: string]: any
}

// 新增：求购信息项类型
export interface BuyingRequestItem {
    id: number;
    title: string;
    description: string;
    price: number;
    tags: string[];
    urgency: string;
    status: string; // 例如 'pending', 'active', 'completed', 'cancelled'
    createdAt: string;
    updatedAt: string;
    isFavorite?: boolean; // 当前用户是否已收藏
    // 可以根据实际后端返回添加更多字段
}

/**
 * 用户登录
 * @param params 登录参数
 * @returns Promise<ApiResponse<UserInfo>>
 */
export async function login(params: LoginParams): Promise<ApiResponse<UserInfo>> {
    return request.post<ApiResponse<UserInfo>>('/user/login', params)
}

/**
 * 用户注册
 * @param params 注册参数
 * @returns Promise<ApiResponse<UserInfo>>
 */
export async function register(params: RegisterParams): Promise<ApiResponse<UserInfo>> {
    return request.post<ApiResponse<UserInfo>>('/user/register', {
        ...params,
        nickname: params.username
    })
}

/**
 * 发送验证码
 * @param phone 手机号
 * @param type 验证码类型 (register|reset)
 * @returns Promise<ApiResponse<null>>
 */
export async function sendVerificationCode(phone: string, type: 'register' | 'reset'): Promise<ApiResponse<null>> {
    return request.post<ApiResponse<null>>('/user/send-code', { phone, type })
}

/**
 * 重置密码
 * @param params 重置密码参数
 * @returns Promise<ApiResponse<null>>
 */
export async function resetPassword(params: ResetPasswordParams): Promise<ApiResponse<null>> {
    return request.post<ApiResponse<null>>('/user/reset-password', params)
}

/**
 * 用户注销
 * @returns Promise<ApiResponse<null>>
 */
export async function logout(): Promise<ApiResponse<null>> {
    return request.post<ApiResponse<null>>('/user/logout')
}

/**
 * 获取用户信息
 * @returns Promise<ApiResponse<UserInfo>>
 */
export async function getUserInfo(): Promise<ApiResponse<UserInfo>> {
    return request.get<ApiResponse<UserInfo>>('/user/info')
}

/**
 * 获取用户个人资料
 * @returns Promise<ApiResponse<UserProfile>>
 */
export async function getUserProfile(): Promise<ApiResponse<UserProfile>> {
    return request.get<ApiResponse<UserProfile>>('/user/profile')
}

/**
 * 获取用户商品列表
 * @param params 分页参数
 * @param status 商品状态(可选)：all, selling, sold, off_shelf, draft
 * @returns Promise<ApiResponse<{ content: ProductItem[], totalElements: number }>>
 */
export async function getUserProducts(params: PaginationParams & { status?: string, userId?: number | string } = {}): Promise<ApiResponse<{ content: ProductItem[], totalElements: number }>> {
    return request.get<ApiResponse<{ content: ProductItem[], totalElements: number }>>('/user/products', { params });
}

/**
 * 获取用户订单列表
 * @param params 分页参数
 * @param status 订单状态(可选)：all, PENDING_PAYMENT, PROCESSING, SHIPPED, COMPLETED
 * @returns Promise<ApiResponse<{ content: OrderItem[], totalElements: number }>>
 */
export async function getUserOrders(params: PaginationParams & { status?: string } = {}): Promise<ApiResponse<{ content: OrderItem[], totalElements: number }>> {
    return request.get<ApiResponse<{ content: OrderItem[], totalElements: number }>>('/user/orders', { params })
}

/**
 * 获取用户收藏列表
 * @returns Promise<ApiResponse<{ content: FavoriteItem[], totalElements: number }>>
 */
export async function getUserFavorites(): Promise<ApiResponse<{ content: FavoriteItem[], totalElements: number }>> {
    // 从本地存储获取userId和token
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    const token = localStorage.getItem('token');

    // 创建参数对象
    const params = { userId: userInfo.id };

    // 创建配置对象
    const config = {
        params,
        headers: {} as Record<string, string>
    };

    // 如果有token，添加到headers
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
    }

    // 发起请求 - 使用新的API路径，不再使用分页参数
    return request.get<ApiResponse<{ content: FavoriteItem[], totalElements: number }>>('/favorites/products', config);
}

/**
 * 获取用户消息列表
 * @param params 分页参数
 * @param read 是否已读(可选)：true, false, all
 * @returns Promise<ApiResponse<{ content: MessageItem[], totalElements: number }>>
 */
export async function getUserMessages(params: PaginationParams & { read?: boolean | 'all' } = {}): Promise<ApiResponse<{ content: MessageItem[], totalElements: number }>> {
    return request.get<ApiResponse<{ content: MessageItem[], totalElements: number }>>('/user/messages', { params })
}

/**
 * 获取用户钱包交易记录
 * @param params 分页参数
 * @returns Promise<ApiResponse<{ content: WalletTransaction[], totalElements: number }>>
 */
export async function getWalletTransactions(params: PaginationParams = {}): Promise<ApiResponse<{ content: WalletTransaction[], totalElements: number }>> {
    return request.get<ApiResponse<{ content: WalletTransaction[], totalElements: number }>>('/user/wallet/transactions', { params })
}

/**
 * 更新用户信息
 * @param data 用户信息
 * @returns Promise<ApiResponse<UserInfo>>
 */
export async function updateUserInfo(data: any): Promise<ApiResponse<UserInfo>> {
    return request.put<ApiResponse<UserInfo>>('/user/info', data)
}

/**
 * 获取指定用户的信息
 * @param userId 用户ID
 * @returns Promise<ApiResponse<UserProfile>>
 */
export async function getSpecificUserInfo(userId: number | string): Promise<ApiResponse<UserProfile>> {
    return request.get<ApiResponse<UserProfile>>(`/user/info`, { params: { userId } });
}

/**
 * 拉黑用户
 * @param targetUserId 目标用户ID
 * @returns Promise<ApiResponse<null>>
 */
export async function blockUser(targetUserId: number): Promise<ApiResponse<null>> {
    return request.post<ApiResponse<null>>('/user/block', { targetUserId });
}

/**
 * 获取黑名单列表
 * @param params 分页参数
 * @returns Promise<ApiResponse<{ content: UserProfile[], totalElements: number }>>
 */
export async function getBlockedUsers(params: PaginationParams = {}): Promise<ApiResponse<{ content: UserProfile[], totalElements: number }>> {
    return request.get<ApiResponse<{ content: UserProfile[], totalElements: number }>>('/user/blocked', { params });
}

/**
 * 取消拉黑用户
 * @param targetUserId 目标用户ID
 * @returns Promise<ApiResponse<null>>
 */
export async function unblockUser(targetUserId: number): Promise<ApiResponse<null>> {
    return request.delete<ApiResponse<null>>(`/user/block/${targetUserId}`);
}

/**
 * 获取用户收藏的求购信息列表
 * @returns Promise<ApiResponse<{ content: PurchaseRequestItem[], totalElements: number }>>
 */
export async function getUserFavoriteRequests(): Promise<ApiResponse<{ content: PurchaseRequestItem[], totalElements: number }>> {
    // 从本地存储获取userId和token
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    const token = localStorage.getItem('token');

    // 创建参数对象
    const params = { userId: userInfo.id };

    // 创建配置对象
    const config = {
        params,
        headers: {} as Record<string, string>
    };

    // 如果有token，添加到headers
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
    }

    // 发起请求
    return request.get<ApiResponse<{ content: PurchaseRequestItem[], totalElements: number }>>('/favorites/requests', config);
}

/**
 * 获取用户的求购列表
 * @param userId 用户ID
 * @param params 查询参数
 * @returns Promise<ApiResponse<{ content: PurchaseRequestItem[], totalElements: number }>>
 */
export async function getUserPurchaseRequests(userId: number, params: any = {}): Promise<ApiResponse<{ content: PurchaseRequestItem[], totalElements: number }>> {
    return request.get<ApiResponse<{ content: PurchaseRequestItem[], totalElements: number }>>(`/requests`, {
        params: {
            userId,
            page: params.page || 1,
            pageSize: params.pageSize || 10,
            ...params
        }
    })
}

export default {
    login,
    register,
    logout,
    getUserInfo,
    getUserProfile,
    getUserProducts,
    getUserOrders,
    getUserFavorites,
    getUserMessages,
    getWalletTransactions,
    updateUserInfo,
    sendVerificationCode,
    resetPassword,
    getSpecificUserInfo,
    blockUser,
    getBlockedUsers,
    unblockUser,
    getUserFavoriteRequests,
    getUserPurchaseRequests
} 